﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Sockets;
using forum.Data;
using System.IO;
using System.Text;
using System.Diagnostics;

namespace forum.ApplicationCode
{
    public class forumConnection
    {
        static char delimiter = '\x1';
        static string endOfMessage = "\n\0\n";
        static System.Net.Sockets.TcpClient clientSocket = null;
        public static Boolean Connect()
        {
            clientSocket = new System.Net.Sockets.TcpClient();
            clientSocket.Connect("ROY-LAP", 61613);
            Debug.WriteLine("+++++++++++connected");
            System.Threading.Thread socketReader = new System.Threading.Thread(readFromSocket);
            socketReader.Start();

            return clientSocket.Connected;
            /* NetworkStream serverStream = clientSocket.GetStream();
             byte[] outStream = System.Text.Encoding.ASCII.GetBytes("hallo\n\0\n\22");
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
             */

        }
        public static void readFromSocket()
        {
            Debug.WriteLine("+++++++++++reading");
            string line = "";
            string readerAccomulate = "";
            using (StreamReader reader = new StreamReader(clientSocket.GetStream(),ASCIIEncoding.ASCII))
            {
                while (!line.Equals("exit"))
                {
                    while (!readerAccomulate.Equals('\x0'+""))
                    {
                        readerAccomulate = reader.ReadLine();
                        Debug.WriteLine("read from socket: "+readerAccomulate);
                        if (!readerAccomulate.Equals('\x0' + ""))
                            line += readerAccomulate;
                    }
                    Console.WriteLine("read: " + line);
                    readerAccomulate = "";
                    parseLine(line);
                    Debug.WriteLine(line);
                    line = "";
                }
            }
        }
        public static void parseLine(string line)
        {
           
            string[] splitedServerLine = line.Split(delimiter);
            Debug.WriteLine("+++++++++++recived: " + line);
            Debug.WriteLine("arraylength: "+splitedServerLine.Length);
            if (String.Compare(splitedServerLine[0], "popupMessage", true) == 0)
            {
                Debug.WriteLine("+++++++++++recivedPopUp: " + line);
                if (String.Compare(splitedServerLine[1], "addedPost", true) == 0)
                {
                    Debug.WriteLine("+++++++++++recived: addedPost number: " + splitedServerLine[2]);
                    webInteractiveMessage.addNewPost(splitedServerLine[2]);
                }
                if (String.Compare(splitedServerLine[1], "addedthread", true) == 0)
                {
                    Debug.WriteLine("+++++++++++recived: addedThread number: " + splitedServerLine[2]);
                    webInteractiveMessage.addNewThread(splitedServerLine[2]);
                }
            }
            else
            {
                if (String.Compare(splitedServerLine[0], "refresh", true) == 0)
                {
                    Debug.WriteLine("+++++++++++recivedRefresh: " + line);
                   
                        if (String.Compare(splitedServerLine[1], "post", true) == 0)
                        {
                             webInteractiveMessage.addRefreshPost(splitedServerLine[2]);
                             Debug.WriteLine("+++++++++++recivedRefreshPost: " + line);
                        }

                         if (String.Compare(splitedServerLine[1], "thread", true) == 0)
                        {
                             webInteractiveMessage.addRefreshThread(splitedServerLine[2]);
                             Debug.WriteLine("+++++++++++recivedRefreshThead: " + line);
                        }
                }

            }

            Debug.WriteLine("num of new thread msg:: " + webInteractiveMessage.newThreadMesaages.Count.ToString());
            Debug.WriteLine("num of new post msg:: " + webInteractiveMessage.newPostMesaages.Count.ToString());
        }

        public static void closeConnection()
        {
            clientSocket.Close();
        }


        public static void addThread(string forumId, string title, string body)
        {
            string message = "";
            message = "addThread" + delimiter + Membership.GetUserName() + delimiter + forumId + delimiter + title
                + delimiter + body + delimiter + endOfMessage;
            NetworkStream serverStream = clientSocket.GetStream();
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(message);
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
        }

        public static void editThread(string threadId, string title, string body)
        {
            using (forumDataContext data = new forumDataContext())
            {
                string forumId = data.sp_getThreadFullDetails(int.Parse(threadId)).FirstOrDefault().subForumId.ToString();
                string message = "";
                message = "EditMsg" + delimiter + Membership.GetUserName() + delimiter + forumId + delimiter +
                   threadId + delimiter + threadId + delimiter + title + delimiter + body + delimiter + "true" + delimiter + endOfMessage;
                NetworkStream serverStream = clientSocket.GetStream();
                byte[] outStream = System.Text.Encoding.ASCII.GetBytes(message);
                serverStream.Write(outStream, 0, outStream.Length);
                serverStream.Flush();
            }

        }

        public static void addPost(string threadId, string title, string body)
        {
            using (forumDataContext data = new forumDataContext())
            {
                string forumId = data.sp_getThreadFullDetails(int.Parse(threadId)).FirstOrDefault().subForumId.ToString();
                string message = "";
                message = "addPost" + delimiter + Membership.GetUserName() + delimiter + forumId + delimiter +
                    threadId + delimiter + threadId + delimiter + title
                    + delimiter + body + delimiter + "true" + delimiter + endOfMessage;
                NetworkStream serverStream = clientSocket.GetStream();
                byte[] outStream = System.Text.Encoding.ASCII.GetBytes(message);
                serverStream.Write(outStream, 0, outStream.Length);
                serverStream.Flush();
            }
        }

        public static void addPostToPost(string postId, string title, string body)
        {
            using (forumDataContext data = new forumDataContext())
            {
                int threadId = data.sp_getPostFullDetails(int.Parse(postId)).FirstOrDefault().threadId;
                string forumId = data.sp_getThreadFullDetails(threadId).FirstOrDefault().subForumId.ToString();
                string message = "";
                message = "addPost" + delimiter + Membership.GetUserName() + delimiter + forumId + delimiter +
                    threadId.ToString() + delimiter + postId + delimiter + title
                    + delimiter + body + delimiter + "false" + delimiter + endOfMessage;
                NetworkStream serverStream = clientSocket.GetStream();
                byte[] outStream = System.Text.Encoding.ASCII.GetBytes(message);
                serverStream.Write(outStream, 0, outStream.Length);
                serverStream.Flush();
            }
        }


        public static void editPost(string postId, string title, string body)
        {
            using (forumDataContext data = new forumDataContext())
            {
                int threadId = data.sp_getPostFullDetails(int.Parse(postId)).FirstOrDefault().threadId;
                string forumId = data.sp_getThreadFullDetails(threadId).FirstOrDefault().subForumId.ToString();
                string message = "";
                message = "EditMsg" + delimiter + Membership.GetUserName() + delimiter + forumId + delimiter +
                    threadId.ToString() + delimiter + postId + delimiter + title
                    + delimiter + body + delimiter + "false" + delimiter + endOfMessage;
                NetworkStream serverStream = clientSocket.GetStream();
                byte[] outStream = System.Text.Encoding.ASCII.GetBytes(message);
                serverStream.Write(outStream, 0, outStream.Length);
                serverStream.Flush();
            }
        }
        public static void login(string userName, string password)
        {


            string message = "";
            message = "login" + delimiter + userName + delimiter + password + delimiter + endOfMessage;
            NetworkStream serverStream = clientSocket.GetStream();
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(message);
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
        }

        public static void viewForum()
        {
            string message = "";
            message = "viewForum" + delimiter + "guest" + delimiter + endOfMessage;
            NetworkStream serverStream = clientSocket.GetStream();
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(message);
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();

        }

        public static void viewSubForum(int subForumId)
        {
            string message = "";
            message = "viewSubForum" + delimiter + "guest" + delimiter + subForumId.ToString() + delimiter + endOfMessage;
            NetworkStream serverStream = clientSocket.GetStream();
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(message);
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();

        }

        public static void viewThread(int subForumId, int threadId)
        {
             string message = "";
            message = "viewThread" + delimiter + "guest" + delimiter + subForumId.ToString() + delimiter + threadId.ToString()
            + delimiter + endOfMessage;
            NetworkStream serverStream = clientSocket.GetStream();
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(message);
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
        }


       public static  void ActiveUser()
        {
            string message = "";
            message = "changeActiveMode" + delimiter + Membership.UserName + delimiter + "true" + delimiter  + endOfMessage;
            NetworkStream serverStream = clientSocket.GetStream();
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(message);
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
        }

       public static void DeActiveUser()
        {
            string message = "";
            message = "changeActiveMode" + delimiter + Membership.UserName + delimiter + "false" + delimiter + endOfMessage;
            NetworkStream serverStream = clientSocket.GetStream();
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(message);
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
        }

       public static void removeModerator(int subForumId, string  moderatorName)
       {
          
           string message = "";
           message = "removeModerator" + delimiter + Membership.UserName + delimiter + subForumId.ToString() + delimiter + moderatorName + delimiter + endOfMessage;
           NetworkStream serverStream = clientSocket.GetStream();
           byte[] outStream = System.Text.Encoding.ASCII.GetBytes(message);
           serverStream.Write(outStream, 0, outStream.Length);
           serverStream.Flush();
       }
    }
}